package com.edu.lec;

import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class WeatherActivity extends Activity{

	ListView listView;
	ArrayList<String> list;	
	ArrayAdapter<String> adapter;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		

		listView = (ListView)findViewById(R.id.listView1);		
		Button btn = (Button) findViewById(R.id.button1);
		
		list = new ArrayList<String>();
		
		btn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				list.clear();
		
				try {
					URL url = new URL("http://www.kma.go.kr/XML/weather/sfc_web_map.xml");
					XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
					XmlPullParser parser = factory.newPullParser();
					parser.setInput(url.openStream(), "utf-8");
					
					String Item = "";
					String ItemName = "";
					String ItemContents = "";
					boolean bSet = false;
					
					int eventType = parser.getEventType();
					
					
					while (eventType != XmlPullParser.END_DOCUMENT) {
						switch (eventType) {
						case XmlPullParser.START_DOCUMENT:
							break;
						case XmlPullParser.END_DOCUMENT:
							break;
						case XmlPullParser.START_TAG:
							String tag = parser.getName();
							if (tag.equals("local")) {
								ItemContents = "";
								String state = parser.getAttributeValue(null,
										"desc");
								String temperature = "섭씨";
								temperature += parser.getAttributeValue(null,
										"ta");
								temperature += "º";
								ItemContents = state + " , " + temperature
										+ "  ";
								bSet = true;
							}
							break;
						case XmlPullParser.END_TAG:
							break;
						case XmlPullParser.TEXT:
							if (bSet) {
								ItemName = "";
								String region = parser.getText();
								ItemName += region + "   - ";
								Item += ItemName + ItemContents;
//								Item += "\n";
								
								// 리스트 소스를 추가할 부분
								list.add(Item);
								Item = "";
								
								adapter.notifyDataSetChanged();
								bSet = false;
							}
							break;
						}
						eventType = parser.next();
					}// while
					
					
				} catch (Exception e) {
					Toast.makeText(v.getContext(), e.getMessage(), 0).show();
				}
			}		
		});// btn.setOnClickListener
		
		adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, list); 
		listView.setAdapter(adapter);

	}
}
